using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using ThreeTeams.Domain.ThreeTeams.Domain.Entities;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 导出产品命令处理程序
    /// </summary>
    public class ExportProductCommandHandler : IRequestHandler<ExportProductCommand, ApiResult<byte[]>>
    {
        private readonly IBaseRepository<Product> _productRepository;

        public ExportProductCommandHandler(IBaseRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public async Task<ApiResult<byte[]>> Handle(ExportProductCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<byte[]>("导出产品");

            try
            {
                var query = _productRepository.GetNewAllList();

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    query = query.Where(p => p.ProductName.Contains(request.ProductName));
                }

                if (!string.IsNullOrEmpty(request.SKU))
                {
                    query = query.Where(p => p.SKU.Contains(request.SKU));
                }

                if (request.ProductTypeId.HasValue)
                {
                    query = query.Where(p => p.ProductTypeId == request.ProductTypeId);
                }

                var products = await query.ToListAsync(cancellationToken);

                // 创建Excel工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("产品列表");

                // 创建表头
                IRow headerRow = sheet.CreateRow(0);
                var headers = new[]
                {
                    "产品名称", "SKU", "规格", "入库价格", "出库价格", "库存预警数量", "重量", "品牌", "型号",
                    "英文名称", "海关编码", "申报价格", "长度", "宽度", "高度", "状态", "备注"
                };

                for (int i = 0; i < headers.Length; i++)
                {
                    headerRow.CreateCell(i).SetCellValue(headers[i]);
                }

                // 填充数据
                for (int i = 0; i < products.Count; i++)
                {
                    var product = products[i];
                    IRow dataRow = sheet.CreateRow(i + 1);

                    dataRow.CreateCell(0).SetCellValue(product.ProductName);
                    dataRow.CreateCell(1).SetCellValue(product.SKU);
                    dataRow.CreateCell(2).SetCellValue(product.Specification ?? "");
                    dataRow.CreateCell(3).SetCellValue(product.PurchasePrice);
                    dataRow.CreateCell(4).SetCellValue(product.SellingPrice);
                    dataRow.CreateCell(5).SetCellValue(product.StockAlert);
                    dataRow.CreateCell(6).SetCellValue(product.Weight);
                    dataRow.CreateCell(7).SetCellValue(product.Brand ?? "");
                    dataRow.CreateCell(8).SetCellValue(product.Model ?? "");
                    dataRow.CreateCell(9).SetCellValue(product.EnglishName ?? "");
                    dataRow.CreateCell(10).SetCellValue(product.CustomsCode ?? "");
                    dataRow.CreateCell(11).SetCellValue(product.DeclaredPrice);
                    dataRow.CreateCell(12).SetCellValue(product.Length);
                    dataRow.CreateCell(13).SetCellValue(product.Width);
                    dataRow.CreateCell(14).SetCellValue(product.Height);
                    dataRow.CreateCell(15).SetCellValue(product.Status);
                    dataRow.CreateCell(16).SetCellValue(product.Notes ?? "");
                }

                // 自动调整列宽
                for (int i = 0; i < headers.Length; i++)
                {
                    sheet.AutoSizeColumn(i);
                }

                // 将工作簿写入内存流
                using var ms = new MemoryStream();
                workbook.Write(ms);
                var bytes = ms.ToArray();

                result.Success(bytes);
            }
            catch (Exception ex)
            {
                result.code = StatusCodeEnum.Fail;
                result.msg = $"导出产品失败：{ex.Message}";
            }

            return result;
        }
    }
} 